package com.bnyy.medicalHousekeeper.base;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bnyy.medicalHousekeeper.UserInfoManager;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.google.gson.internal.LinkedTreeMap;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public abstract class BaseActivityImpl extends BaseActivity {

    public RequestManager requestManager;
    SharedPreferences sharedPreferences;
    public UserInfoManager userInfoManager;

    @Override
    public AppCompatActivity getSelfActivity() {
        return this;
    }

    @Override
    public boolean registerEventBus() {
        return false;
    }

    @Override
    public boolean unuseRefreshLayout() {
        return false;
    }

    @Override
    public OnRefreshListener registerOnRefreshListener() {
        return null;
    }

    @Override
    public OnLoadMoreListener registerOnLoadMoreListener() {
        return null;
    }

    @Override
    public LocationPermissionIsGrantListener registerLocationPermissionIsGrantListener() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestManager = RequestManager.getInstance();
        userInfoManager = UserInfoManager.getInstance();

        if (!(getSelfActivity() instanceof UnnecessaryLogin)
                && App.getUser() == null) {
//            finish();
//            App.loginInvalid();
//            show(mContext, LoginActivity.class);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!(getSelfActivity() instanceof UnnecessaryLogin)
                && App.getUser() == null) {
            App.restart();
//                show(mContext, LoginActivity.class);
        }
    }

    public interface UnnecessaryLogin {
    }

    public interface UnnecessaryRequestGlobalParams {
    }

    public void compressAndUploadImage(Uri uri, OnUploadFinishListener l) {
        compress(uri, new OnCompressFinishListener() {
            @Override
            public void onSuccess(File file) {
                upload(file, l);
            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }

    public void compressAndUploadImage(ArrayList<String> imagePaths, OnUploadFinishListener l) {
        for (String s : imagePaths) {
            compressAndUploadImage(s, l);
        }
    }

    public void compressAndUploadImage(String imagePath, OnUploadFinishListener l) {
        compress(imagePath, new OnCompressFinishListener() {
            @Override
            public void onSuccess(File file) {
                upload(file, l);
            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }

    public void compress(Uri uri, OnCompressFinishListener l) {
        ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在压缩图片");
        Luban.with(this)
                .load(uri)
                .ignoreBy(100)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        Log.e("Luban", "onStart");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        Log.e("Luban", "onSuccess file = " + file.getAbsolutePath());
                        l.onSuccess(file);
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        Log.e("Luban", "onError e = " + e.toString());
                        Toast.makeText(mContext, "图片压缩失败，请重试", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        l.onError(e);
                    }
                }).launch();
    }

    public void compress(String imagePath, OnCompressFinishListener l) {
        ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在压缩图片");
        Luban.with(this)
                .load(imagePath)
                .ignoreBy(100)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        Log.e("Luban", "onStart");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        Log.e("Luban", "onSuccess file = " + file.getAbsolutePath());
                        l.onSuccess(file);
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        Log.e("Luban", "onError e = " + e.toString());
                        Toast.makeText(mContext, "图片压缩失败，请重试", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        l.onError(e);
                    }
                }).launch();
    }

    public void upload(File file, OnUploadFinishListener l) {
//        ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在上传图片");
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        try {
            builder.addFormDataPart("files", URLEncoder.encode(file.getName(), "UTF-8"), requestBody);//files 文件上传参数
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<MultipartBody.Part> parts = builder.build().parts();
        requestManager.request(requestManager.mRetrofitServiceServer.uploadFiles(parts),
                new BaseObserverImpl<LinkedTreeMap<String, String[]>>() {
                    @Override
                    public void onSuccess(LinkedTreeMap<String, String[]> linkedTreeMap) {
                        super.onSuccess(linkedTreeMap);
                        String[] strings = linkedTreeMap.get("fiels");
                        if (strings != null && strings.length > 0) {
                            l.onSuccess(strings[0]);
                        } else {
                            l.onError(new Exception());
                        }
//                        progressDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.makeText(mContext, "图片上传失败，请重新上传", Toast.LENGTH_SHORT).show();
//                        progressDialog.dismiss();
                    }
                });
    }

    public interface OnCompressFinishListener {
        void onSuccess(File file);

        void onError(Throwable e);
    }

    public abstract class OnUploadFinishListener {
        public abstract void onSuccess(String url);

        public void onError(Throwable e) {

        }
    }
}



































